<template>
  <div class="page">
    <q-dialog v-model="show" persistent>
      <q-card class="card-body">
        <q-card-section>
          <div class="text-h6">添加歌手</div>
        </q-card-section>

        <q-separator />

        <q-form
          @submit="isEdit ? editArtist() : createArtist()"
          class="q-gutter-md"
        >
          <q-card-section class="q-pt-none">
            <q-input
              dense
              v-model="artist.name"
              label="歌手名"
              autofocus
              @keyup.enter="show = false"
              :rules="[val => (val && val.length > 0) || '未输入歌手名']"
              placeholder="例:周杰伦"
            />

            <q-input
              dense
              v-model="artist.remark"
              type="textarea"
              label="备注"
              autofocus
              @keyup.enter="show = false"
              placeholder="例:这是一首好听的歌"
            />
          </q-card-section>

          <q-card-section>
            <uploader v-model:file="artist.photo" label="上传歌手图片" />
          </q-card-section>

          <q-separator />

          <q-card-actions align="right" class="text-primary">
            <q-btn flat label="取消" color="primary" v-close-popup />
            <q-btn label="确认" type="submit" color="primary" />
          </q-card-actions>
        </q-form>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { create, update } from '../../api/artist/artist';
import MyNotify from '../../utils/notify';
import uploader from '../../components/uploader.vue';

const props = defineProps({
  data: {
    type: Object,
    default() {
      return null;
    }
  }
});

const show = ref(true);
const isEdit = ref(Boolean(props.data));
// const photo = ref(null);
const artist = reactive(
  props.data || {
    name: '',
    remark: '',
    photo: null
  }
);

const emit = defineEmits(['createSuccess', 'editSuccess']);

const createArtist = () => {
  create({
    name: artist.name,
    remark: artist.remark,
    photoId: artist.photo.id
  }).then(createArtist => {
    show.value = false;
    emit('createSuccess');
    MyNotify.success(`歌手《${createArtist.name}》创建成功`);
  });
};
const editArtist = () => {
  update(artist.id, {
    name: artist.name,
    remark: artist.remark,
    photoId: artist.photo.id
  }).then(savedArtist => {
    show.value = false;
    emit('editSuccess');
    MyNotify.success(`音乐《${savedArtist.name}》编辑成功`);
  });
};
</script>

<style scoped></style>
